package com.example.gank.slice;

import com.example.gank.ResourceTable;
import com.example.gank.util.DisplayUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;

import ohos.agp.utils.Color;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.service.WindowManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.resource.NotExistException;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.TouchEvent;
import ohos.utils.net.Uri;

import java.io.IOException;
/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class MainAbilitySlice extends AbilitySlice{
    private DirectionalLayout layoutLeft;
    private DirectionalLayout layoutRight;
    private Text tvThme;
    private CommonDialog commonDialog;
    private Text intentText;
    private DirectionalLayout dirTitle;
    private int index = 0;
    private int downY;
    private int upY;
    private int upX;
    private int downX;
    private DirectionalLayout textRefresh;
    private Text all;
    private Text lucky;
    private Text phone;
    private Text ios;
    private Text video;
    private Text js;
    private Text expand;
    private Text app;
    private Text recommend;
    private Image image;
    private Text textTitle;
    private AnimatorProperty mAnimator;
    private Image imageHead;
    private Text intentText1;
    private Text intentText2;
    private Text intentText3;
    private Text intentText4;
    private Text intentText5;
    private Text intentText6;
    private Text intentText7;
    private static final String URL = "https://www.baidu.com" ;
    private static final int INDEX_ZERO = 0 ;
    private static final int INDEX_FIRST = 1 ;
    private static final int INDEX_SECOND = 2 ;
    private static final int INDEX_THIRD = 3 ;
    private static final int IMAGE_WIDTH = 80 ;
    private static final int IMAGE_RADIA = 360 ;
    private static final int DELAY_TIME = 2500 ;
    private static final int MOVE_DISTANCE = 200 ;
    private static final int MOVE_WIDTH = 800 ;
    private static final RgbColor RGB_ZERO = new RgbColor(204, 194, 34);
    private static final RgbColor RGB_FIRST = new RgbColor(187, 22, 0);
    private static final RgbColor RGB_SECOND = new RgbColor(109, 187, 0);
    private static final RgbColor RGB_THIRD = new RgbColor(0, 106, 187);
    private final HiLogLabel lable = new HiLogLabel(HiLog.LOG_APP, 0x00201, "");
    private EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner()){
        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            mAnimator.cancel();
            textRefresh.setVisibility(Component.HIDE);
        }
    };

    /**
     * 页面创建
     * @param intent
     */
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS);
        super.setUIContent(ResourceTable.Layout_ability_main);
        layoutLeft = (DirectionalLayout) findComponentById(ResourceTable.Id_lin_left);
        layoutRight = (DirectionalLayout) findComponentById(ResourceTable.Id_lin_right);
        textRefresh = (DirectionalLayout) findComponentById(ResourceTable.Id_text_refresh);
        tvThme = (Text) findComponentById(ResourceTable.Id_tv_theme);
        image = (Image) findComponentById(ResourceTable.Id_image);
        intentText = (Text) findComponentById(ResourceTable.Id_intentText);
        dirTitle = (DirectionalLayout) findComponentById(ResourceTable.Id_lin_title);
        all = (Text) findComponentById(ResourceTable.Id_text_all);
        lucky = (Text) findComponentById(ResourceTable.Id_text_lucky);
        phone = (Text) findComponentById(ResourceTable.Id_text_phone);
        ios = (Text) findComponentById(ResourceTable.Id_text_ios);
        video = (Text) findComponentById(ResourceTable.Id_text_video);
        js = (Text) findComponentById(ResourceTable.Id_text_js);
        expand = (Text) findComponentById(ResourceTable.Id_text_expand);
        app = (Text) findComponentById(ResourceTable.Id_text_app);
        recommend = (Text) findComponentById(ResourceTable.Id_text_recommend);
        intentText1 = (Text) findComponentById(ResourceTable.Id_intent_text0);
        intentText2 = (Text) findComponentById(ResourceTable.Id_intent_text1);
        intentText3 = (Text) findComponentById(ResourceTable.Id_intent_text2);
        intentText4 = (Text) findComponentById(ResourceTable.Id_intent_text3);
        intentText5 = (Text) findComponentById(ResourceTable.Id_intent_text4);
        intentText6 = (Text) findComponentById(ResourceTable.Id_intent_text5);
        intentText7 = (Text) findComponentById(ResourceTable.Id_intent_text6);
        imageHead = (Image) findComponentById(ResourceTable.Id_imageHead);
        textTitle = (Text) findComponentById(ResourceTable.Id_text_title);
        imageHead.setCornerRadius(Float.valueOf(DisplayUtils.vp2px(getContext(),IMAGE_WIDTH))/INDEX_SECOND);
        commonDialog= new CommonDialog(this);
        layoutRight.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent event) {
                switch (event.getAction()) {
                    case TouchEvent.PRIMARY_POINT_DOWN:
                        downY = getRawY(event);
                        downX = getRawX(event);
                        break;
                    case TouchEvent.CANCEL:
                    case TouchEvent.PRIMARY_POINT_UP:
                        upY = getRawY(event);
                        upX = getRawX(event);
                        setMove();
                        break;
                    case TouchEvent.POINT_MOVE:
                        break;
                }
                return true;
            }
        });

        intentText.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent1 = new Intent();
                intent1.setAction("android.intent.action.VIEW");
                Uri uri = Uri.parse(URL);
                intent1.setUri(uri);
                startAbility(intent1);
            }
        });
        tvThme.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                showThemeDialog();
            }
        });

        all.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                textTitle.setText("全部");
                setDone();
            }
        });
        lucky.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                textTitle.setText("福利");
                setDone();
            }
        });
        phone.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                textTitle.setText("真机");
                setDone();
            }
        });
        ios.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                textTitle.setText("ios");
                setDone();
            }
        });
        video.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                textTitle.setText("休息视频");
                setDone();
            }
        });
        js.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                textTitle.setText("前端");
                setDone();
            }
        });
        expand.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                textTitle.setText("拓展资源");
                setDone();
            }
        });
        app.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                textTitle.setText("App");
                setDone();
            }
        });
        recommend.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                textTitle.setText("瞎推荐");
                setDone();
            }
        });
        intentText1.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent1 = new Intent();
                intent1.setAction("android.intent.action.VIEW");
                Uri uri = Uri.parse(URL);
                intent1.setUri(uri);
                startAbility(intent1);
            }
        });
        intentText2.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent1 = new Intent();
                intent1.setAction("android.intent.action.VIEW");
                Uri uri = Uri.parse(URL);
                intent1.setUri(uri);
                startAbility(intent1);
            }
        });
        intentText3.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent1 = new Intent();
                intent1.setAction("android.intent.action.VIEW");
                Uri uri = Uri.parse(URL);
                intent1.setUri(uri);
                startAbility(intent1);
            }
        });
        intentText4.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent1 = new Intent();
                intent1.setAction("android.intent.action.VIEW");
                Uri uri = Uri.parse(URL);
                intent1.setUri(uri);
                startAbility(intent1);
            }
        });
        intentText5.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent1 = new Intent();
                intent1.setAction("android.intent.action.VIEW");
                Uri uri = Uri.parse(URL);
                intent1.setUri(uri);
                startAbility(intent1);
            }
        });
        intentText6.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent1 = new Intent();
                intent1.setAction("android.intent.action.VIEW");
                Uri uri = Uri.parse(URL);
                intent1.setUri(uri);
                startAbility(intent1);
            }
        });
        intentText7.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent1 = new Intent();
                intent1.setAction("android.intent.action.VIEW");
                Uri uri = Uri.parse(URL);
                intent1.setUri(uri);
                startAbility(intent1);
            }
        });
    }

    /**
     * 展示主题弹窗
     */
    public void showThemeDialog() {

        Component component = LayoutScatter.getInstance(getContext())
                .parse(ResourceTable.Layout_dialog_custom_layout, null, true);
        commonDialog.setContentCustomComponent(component);
        Text cancle = (Text) component.findComponentById(ResourceTable.Id_cancle);
        Text title = (Text) component.findComponentById(ResourceTable.Id_tv_title);
        Text save = (Text) component.findComponentById(ResourceTable.Id_save);
        RadioButton radioButton1 = (RadioButton) component.findComponentById(ResourceTable.Id_rb_red);
        RadioButton radioButton2 = (RadioButton) component.findComponentById(ResourceTable.Id_rb_yellow);
        RadioButton radioButton3 = (RadioButton) component.findComponentById(ResourceTable.Id_rb_green);
        RadioButton radioButton4 = (RadioButton) component.findComponentById(ResourceTable.Id_rb_blue);
        commonDialog.show();
        cancle.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                commonDialog.hide();
            }
        });
        save.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                commonDialog.hide();
                if (index == INDEX_ZERO) {
                    changeTheme(RGB_ZERO,save,cancle,title,ResourceTable.Color_yellow);
                } else if (index == INDEX_FIRST) {
                    changeTheme(RGB_FIRST,save,cancle,title,ResourceTable.Color_red);
                } else if (index == INDEX_SECOND) {
                    changeTheme(RGB_SECOND,save,cancle,title,ResourceTable.Color_green);
                } else if (index == INDEX_THIRD) {
                    changeTheme(RGB_THIRD,save,cancle,title,ResourceTable.Color_blue);
                }
            }
        });
        radioButton1.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                index = INDEX_ZERO;
            }
        });
        radioButton2.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                index = INDEX_FIRST;
            }
        });
        radioButton3.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                index = INDEX_SECOND;
            }
        });
        radioButton4.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                index = INDEX_THIRD;
            }
        });
    }

    /**
     * 改变主题
     * @param rgb 颜色值
     */
    public void changeTheme(RgbColor rgb, Text save, Text cancel, Text title,int color ) {
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(rgb);
        layoutLeft.setBackground(shapeElement);
        dirTitle.setBackground(shapeElement);

        ResourceManager resourceManager = this.getResourceManager();

        try {
            save.setTextColor(new Color(resourceManager.getElement(color).getColor()));
            cancel.setTextColor(new Color(resourceManager.getElement(color).getColor()));
            title.setTextColor(new Color(resourceManager.getElement(color).getColor()));
            intentText1.setTextColor(new Color(resourceManager.getElement(color).getColor()));
            intentText.setTextColor(new Color(resourceManager.getElement(color).getColor()));
            intentText2.setTextColor(new Color(resourceManager.getElement(color).getColor()));
            intentText3.setTextColor(new Color(resourceManager.getElement(color).getColor()));
            intentText4.setTextColor(new Color(resourceManager.getElement(color).getColor()));
            intentText5.setTextColor(new Color(resourceManager.getElement(color).getColor()));
            intentText6.setTextColor(new Color(resourceManager.getElement(color).getColor()));
            intentText7.setTextColor(new Color(resourceManager.getElement(color).getColor()));
        } catch (IOException e) {
            HiLog.error(lable,"", e);
        } catch (NotExistException e) {
            HiLog.error(lable,"", e);
        } catch (WrongTypeException e) {
            HiLog.error(lable,"", e);
        }
    }


    /**
     * 获取横向偏移值
     * @param ev
     * @return
     */
    private int getRawY(TouchEvent ev) {
        int sumY =  INDEX_ZERO;
        int count = ev.getPointerCount();
        for (int i = 0; i < count; i++) {
            sumY += (int)ev.getPointerScreenPosition(i).getY();
        }
        return sumY / count;
    }

    /**
     * 获取纵向偏移值
     * @param ev
     * @return
     */
    private int getRawX(TouchEvent ev) {
        int sumX =  INDEX_ZERO;
        int count = ev.getPointerCount();

        for (int i = 0; i < count; i++) {
            sumX += (int)ev.getPointerScreenPosition(i).getX();
        }
        return (int) (sumX / count);
    }

    /**
     *设置动画
     */
    public void setAnimator(){
        textRefresh.setVisibility(Component.VISIBLE);
        mAnimator = image.createAnimatorProperty();
        mAnimator.setDuration(MOVE_WIDTH).rotate(IMAGE_RADIA).setTarget(image).setLoopedCount(Animator.INFINITE) .start();
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    sleep(DELAY_TIME);
                    InnerEvent innerEvent = InnerEvent.get();
                    eventHandler.sendEvent(innerEvent);
                } catch (InterruptedException e) {
                    HiLog.error(lable,"", e);
                }
            }
        }.start();
    }

    /**
     * 设置上层view 左移
     */
    public void setMove(){
        if (upX - downX>MOVE_DISTANCE){
            layoutRight.setTranslationX(MOVE_WIDTH);
        }else if (upY-downY >MOVE_DISTANCE){
            setAnimator();
        }else if (downX-upX>MOVE_DISTANCE){
            layoutRight.setTranslationX(INDEX_ZERO);
        }
    }

    /**
     * 复位
     */
    public void setDone(){
        layoutRight.setTranslationX(INDEX_ZERO);
    }

}
